#!/bin/bash

function pkg_manager() {
  # Judge the software package management mechanism by OS version
  os_version=$(cat /etc/os-release)
  if [[ ${os_version} =~ "openEuler" ]] || [[ ${os_version} =~ "Red Hat" ]] || [[ ${os_version} =~ "CentOS" ]]; then
    return 0
  elif [[ ${os_version} =~ "Ubuntu" ]] || [[ ${os_version} =~ "Debian" ]]; then
    return 1
  else
    echo "[ERROR] Linux distributions not support"
    exit 1
  fi
}

function install_rpm() {
  yum_install_rpm_name=$1
  apt_install_rpm_name=$2
  # Check if rpm is installed
  os_version=$(pkg_manager)
  if [[ $? -eq 0 ]]; then
    install_rpm_name=${yum_install_rpm_name}
    install_status=$(rpm -qa "${install_rpm_name}" 2>&1)
  else
    install_rpm_name=${apt_install_rpm_name}
    install_status=$(dpkg -s "${install_rpm_name}" 2>&1)
  fi

  if [[ -z ${install_status} ]] || [[ ${install_status} =~ "is not installed" ]] || [[ ${install_status} =~ "没有安装" ]]; then
    echo "[INFO] ${install_rpm_name} is not installed, start install it"
    sudo apt install "${install_rpm_name}" -y >/dev/null 2>&1
    apt_install=$?
    sudo yum install "${install_rpm_name}" -y >/dev/null 2>&1
    yum_install=$?
    if [[ ${apt_install} -eq 1 ]] && [[ ${yum_install} -eq 1 ]]; then
      echo "[ERROR] ${install_rpm_name} install failed"
      exit 1
    fi
  fi
}
